﻿using OAuth;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Smolder.UI
{
    public partial class SysTrayApp : Form
    {
        public const string RequestTokenUrl = @"http://api.smugmug.com/services/oauth/getRequestToken.mg";
        public const string AuthorizeUrl = @"http://api.smugmug.com/services/oauth/authorize.mg";
        public const string AccessTokenUrl = @"http://api.smugmug.com/services/oauth/getAccessToken.mg";

        public SysTrayApp()
        {
            _trayMenu = new ContextMenu();
            _trayMenu.MenuItems.Add("Exit", OnExit);

            _trayIcon = new NotifyIcon();
            _trayIcon.Text = "Smolder";
            _trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40);

            _trayIcon.ContextMenu = _trayMenu;
            _trayIcon.Visible = true;
        }

        protected override void OnLoad(EventArgs e)
        {
            Visible = false;
            ShowInTaskbar = false;

            base.OnLoad(e);
            string token = Properties.Settings.Default.OAuthToken;
            string secret = Properties.Settings.Default.OAuthTokenSecret;
            if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(secret)) 
            {
                InitiateAppAuthorizationProcess();
            }
        }

        private void InitiateAppAuthorizationProcess()
        {
            Tuple<string, string> oAuthData = FetchOAuthSecret();
            OAuthManager manager = new OAuthManager(oAuthData.Item1, oAuthData.Item2);
            OAuthResponse requestToken = manager.AcquireRequestToken(RequestTokenUrl, "GET");
            string oauthToken = requestToken["oauth_token"];
            string oauthTokenSecret = requestToken["oauth_token_secret"];
            System.Diagnostics.Process.Start(string.Format("{0}?oauth_token={1}&Access=Full&Permissions=Modify", AuthorizeUrl, oauthToken));
            Console.WriteLine("Please accept the software in popup then press any key to continue");
            Console.ReadKey();
            OAuthResponse accessToken = manager.AcquireAccessToken(AccessTokenUrl, "GET", oauthTokenSecret);
            File.WriteAllText("accessData.txt", string.Format("AccessToken={0}\nAccessTokenSecret={1}", accessToken["oauth_token"], accessToken["oauth_token_secret"]));
        }

        //To be replaced in released code - I.E. secret key will need to be embedded somehow
        //Release code should at least be obfuscated...
        private Tuple<string, string> FetchOAuthSecret()
        {
            try
            {
                var data = File.ReadAllLines(@"C:\smolder.oauth");
                return new Tuple<string, string>(data[0], data[1]);
            }
            catch (Exception e)
            { 
                throw new Exception(@"There needs to be a file C:\smolder.oauth containing application oauth information for the application to continue",e);
            }
        }

        private void OnExit(object sender, EventArgs e)
        {
            Application.Exit();
        }

        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                // Release the icon resource.
                _trayIcon.Dispose();
            }

            base.Dispose(isDisposing);
        }

        private NotifyIcon _trayIcon;
        private ContextMenu _trayMenu;
    }
}


